package org.ofbiz.wvtools;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.UtilUUID;

import javolution.util.FastList;
import javolution.util.FastMap;
import net.lingala.zip4j.ZipFile;

public class PictureServices {
    public static String module = PictureServices.class.getName();

    public static final String OFBIZ_HOME = System.getProperty("ofbiz.home");
//	
//	public static void main(String[] args) throws Exception {
//	
//		
//		String path ="D:\\workspace\\cross_server\\hot-deploy\\sys\\webapp\\sys\\images\\coimages\\p8001";
//		System.out.println("path ="+path);
//		listSubFileName(path);
//		
//		
//		System.out.println("path ="+path+"\\20200507");
//		listSubFileName(path+"\\20200507");
//		
//		System.out.println("path ="+path+"\\20200507\\001");
//		listSubFileName(path+"\\20200507\\001");
//	}


    // 读取文件夹
    public static Map<String, Object> listFileNameByPath(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map result = ServiceUtil.returnSuccess();
	// Delegator delegator = dctx.getDelegator();
	String filePath = (String) context.get("filePath");
	String companyId = (String) context.get("companyId");
	List nfsList = new ArrayList();

	String basePath = "/hot-deploy/sys/webapp/sys/images/coimages/";
	String path = OFBIZ_HOME + basePath + "/" + companyId;
	if (UtilValidate.isNotEmpty(filePath)) {
	    path = "/" + filePath;
	}
	File file = new File(path);
	File[] files = file.listFiles();
	if (UtilValidate.isNotEmpty(files)) {
	    for (File fileIndex : files) {
		nfsList.add(fileIndex.getName());
	    }
	}
	result.put("nfsList", nfsList);

	return result;
    }

    // 压缩包上传.保存到对应文件夹
    @SuppressWarnings("resource")
    public static Map<String, Object> uploadByCompress(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	LocalDispatcher dispatcher = dctx.getDispatcher();
	String companyId = (String) context.get("companyId");
	ByteBuffer dataBytes = (ByteBuffer) context.get("uploadFile");
	String uploadFileFileName = (String) context.get("uploadFileFileName");
	try {
	    if (UtilValidate.isNotEmpty(uploadFileFileName)) {
		String zipFilePath = OFBIZ_HOME + "/hot-deploy/sys/webapp/sys/images/";
		Debug.log("fileName========" + uploadFileFileName);
		String extendName = uploadFileFileName.substring(uploadFileFileName.lastIndexOf("."));
		String uuid = UtilUUID.uuidTomini();
		String imagePath = uuid + extendName.toLowerCase();
		File file = new File(zipFilePath + "cozip/" + imagePath);
		boolean append = false;
		FileChannel wChannel = new FileOutputStream(file, append).getChannel();
		wChannel.write(dataBytes);
		wChannel.close();
		String destPath = zipFilePath + "coimages/" + companyId;
		if (".zip".equals(extendName)) {
		    unPackZip(file, destPath);
		} else {
		    return ServiceUtil.returnError("压缩包格式不正确,只支持zip!");
		}
		file.delete();
		//最好做个异步操作
		dispatcher.runAsync("thumbnailRunner", UtilMisc.toMap("destPath", destPath));
		// 使用递归的方法调用
//		List<File> imgList = FastList.newInstance();
//		traverseFolder(imgList, destPath);
//		ClipRunner(imgList);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return result;
    }
    
    public static Map<String, Object> thumbnailRunner(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	try {
	    String destPath = (String) context.get("destPath");
	    // 使用递归的方法调用
	    List<File> imgList = FastList.newInstance();
	    traverseFolder(imgList, destPath);
	    ClipRunner(imgList);
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return result;
    }
    
    public static void main(String[] args) {
	List<File> imgList = FastList.newInstance();
	traverseFolder(imgList,
		"E:\\workplace\\cross\\cross_server\\hot-deploy\\sys\\webapp\\sys\\images\\coimages\\c8008");
	try {
	    ClipRunner(imgList);
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }

    public static void ClipRunner(List<File> imgList) throws IOException {
	for (int i = 0; i < imgList.size(); i++) {
	    File imageFile = imgList.get(i);
	    if (imageFile.exists()) {
		String imgName = imageFile.getName();
//		String fileName = imgName.toLowerCase();
		String firstName = imgName.substring(0, imgName.lastIndexOf("."));
		//System.out.println(firstName);
		String lastName = imgName.substring(imgName.lastIndexOf("."), imgName.length());

		String inFilePath = imageFile.getPath();
		inFilePath = inFilePath.replace(imgName, firstName + "_100x100" + lastName);

		File newFile = new File(inFilePath);
		String srcImgPath = newFile.getAbsoluteFile().toString();

		Image srcFile = ImageIO.read(imageFile);
		if(UtilValidate.isNotEmpty(srcFile)) {
		    int w = srcFile.getWidth(null);
			int h = srcFile.getHeight(null);
			int width = 100;
			int height = 0;
			double bili;
			if (w > width) {
			    bili = width / (double) w;
			    height = (int) (h * bili);
			} else {
			    width = w;
			    height = h;
			}
			BufferedImage buffImg = null;
			lastName = lastName.substring(1, lastName.length());
			//System.out.println(lastName);
			if (lastName.equals("png")) {
			    buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
			    // if (lastName.equals("jpg") || lastName.equals("jpeg") || lastName.equals("bmp")) 
			} else{
			    buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			}
			
			Graphics2D graphics = buffImg.createGraphics();
			graphics.setBackground(new Color(255, 255, 255));
			graphics.setColor(new Color(255, 255, 255));
			graphics.fillRect(0, 0, width, height);
			graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
			ImageIO.write(buffImg, lastName, new File(srcImgPath));
		}else {
		    //Debug.log("图片路径无法找到==="+imageFile.getPath());
		}
	    }
	}
    }

    public static void traverseFolder(List<File> imgList, String path) {
	File file = new File(path);
	if (file.exists()) {
	    File[] files = file.listFiles();
	    if (null == files || files.length == 0) {
		System.out.println("文件夹是空的!");
		return;
	    } else {
		for (File file2 : files) {
		    if (file2.isDirectory()) {
//	                        System.out.println("文件夹:    " + file2.getName());
			traverseFolder(imgList, file2.getAbsolutePath());
		    } else {
			String imgName = file2.getName();
			String fileName = imgName.toLowerCase();
			String firstName = imgName.substring(0, imgName.lastIndexOf("."));
			String lastName = imgName.substring(imgName.lastIndexOf("."), imgName.length());
			if (fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".png")
				|| fileName.contains(".bmp") || fileName.contains(".gif")) {
			    if (!firstName.contains("_100x100")) {
				String filePath = file2.getPath();
				filePath = filePath.replace(imgName, firstName + "_100x100" + lastName);
				File file100 = new File(filePath);
				if (!file100.exists()) {
				    imgList.add(file2);
				}
				//System.out.println("文件:      " + filePath + "后缀: " + lastName + " 前缀" + firstName);
			    }
			}
		    }
		}
	    }
	} else {
	    System.out.println("文件不存在!");
	}
    }

    public static void unPackZip(File zipFile, String destPath) {
	try {
	    if (!zipFile.exists()) {
		zipFile.mkdir();
	    }
	    ZipFile zip = new ZipFile(zipFile);
	    /* zip4j默认用GBK编码去解压,这里设置编码为GBK的 */
	    zip.setCharset(Charset.forName("GBK"));
	    zip.extractAll(destPath);
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
    }

}
